package cs236369.webserver.queue.managers;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;

import cs236369.webserver.DTOs.Request;
import cs236369.webserver.queue.handlers.Worker;

public class SocketTaskManager extends TaskManager<Socket> {

	private final RequestTaskManager rtm;
	private final HttpParams params;
	
	public SocketTaskManager(int sizeOfSocketQueue , RequestTaskManager rtm, HttpParams params) {
		super(sizeOfSocketQueue);
		this.rtm = rtm;
		this.params = params;
	}

	@Override
	protected Thread newWorker(ConcurrentLinkedQueue<Socket> taskQueue) {
		return new SocketHandler(taskQueue);
	}
	
	class SocketHandler extends Worker<Socket> {

		public SocketHandler(ConcurrentLinkedQueue<Socket> queue) {
			super(queue);
		}

		@Override
		protected void handleTask(Socket socket) {
			// Read the request parse it then put the parsed request object in the
			// queue
			DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
			try {
				conn.bind(socket, params);
				HttpRequest req = conn.receiveRequestHeader();
	            Request r = new Request(conn,req);
	            rtm.enQueue(r);
			} catch (IOException e) {
				System.err.println("I/O Error on Socket: " + socket + " in thread " + this);
			} catch (HttpException e) {
				System.err.println("HTTP Error on Socket: " + socket + " in thread " + this);
			}
		}

	}

}
